<template>
  <div>
    <el-upload
      list-type="picture-card"
      accept=".png,.jpg,.jpeg"
      :action="uploadUrl"
      name="uploadFile"
      :data="{folder}"

      :before-upload="beforeUpload"
      :file-list="fileList"

      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview"
    >
      <i class="el-icon-plus" />
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过4M</div>
    </el-upload>

    <el-dialog v-if="dialogVisible" :visible.sync="dialogVisible">
      <img width="100%" :src="fileList[0].url" alt="">
    </el-dialog>
  </div>
</template>

<script>

import { uploadUrl } from '@/api/upload'

export default {
  name: 'SingleImageUpload',
  props: {
    value: {
      type: String,
      default: ''
    },
    folder: {
      type: String,
      default: 'common'
    }
  },
  data() {
    return {
      showFileList: false,
      loading: false,
      fileList: [],
      uploadUrl,
      dialogVisible: false
    }
  },
  computed: {

  },
  methods: {
    handleRemove(file, fileList) {
      this.emitInput(fileList)
    },
    emitInput(val) {
      this.$emit('input', val)
    },
    handlePreview(file) {
      this.dialogVisible = true
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt4M = file.size / 1024 / 1024 < 4

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      }
      if (!isLt4M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }

      return isJPG && isLt4M
    },
    handleUploadSuccess(res, file) {
      this.showFileList = true
      this.fileList.pop()
      this.fileList.push({ name: res.data.fileName, url: res.data.fullFilePath })
      this.emitInput(this.fileList[0].url)
    }
  }

}
</script>

<style scoped>

</style>
